package com.jianyun.jyzs.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.CrmAdapter;
import com.jianyun.jyzs.bean.CrmSearchBean;
import com.jianyun.jyzs.dao.CrmDao;
import com.jianyun.jyzs.http.CrmHelper;
import com.jianyun.jyzs.http.CrmHttpHelper;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.StatusBarUtils;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.widget.CrmConditionSearch;
import com.jianyun.jyzs.widget.CrmTimeSearch;
import com.jianyun.jyzs.widget.ErecyclerView;
import com.jrmf360.rylib.common.util.KeyboardUtil;
import com.omadahealth.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.omadahealth.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * CRM 主页
 * Created by yangshijun on 2018/6/4.
 */

public class CrmActivity extends AppCompatActivity implements SwipyRefreshLayout.OnRefreshListener {
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.calendar)
    ImageView calendar;
    @BindView(R.id.add)
    ImageView add;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.app_crm_search_part_text)
    CheckBox appCrmSearchPartText;
    @BindView(R.id.app_crm_search_part)
    LinearLayout appCrmSearchPart;
    @BindView(R.id.app_crm_searchTime_text)
    CheckBox appCrmSearchTimeText;
    @BindView(R.id.app_crm_searchTime)
    LinearLayout appCrmSearchTime;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.enterpriseName)
    EditText enterpriseName;
    @BindView(R.id.app_crm_search_img)
    LinearLayout appCrmSearchImg;
    @BindView(R.id.loadButton)
    Button loadButton;
    @BindView(R.id.loadRl)
    RelativeLayout loadRl;
    @BindView(R.id.emptyview)
    RelativeLayout emptyview;
    @BindView(R.id.crmList)
    ErecyclerView crmRecyclerView;
    @BindView(R.id.swipy)
    SwipyRefreshLayout swipy;


    private CrmDao crmDao;
    private String userId = "";//70b21776-38df-4802-9671-1b9e8baff210
    private List<CrmSearchBean.ListCrm> mDatas;
    private CrmAdapter crmAdapter;
    private int page = 1;
    private String orderTime = "ldsj  asc";//时间排序 默认正序
    private String khzt;//客户状态；
    private String khxz;//客户性质
    //private boolean isAgain = false;
    private String enterpriseCode;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_crm);
        ButterKnife.bind(this);
        initData();
        initView();
        initCretaLisener();
    }



    private void initData() {
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        crmDao = new CrmDao(this);
        mDatas = new ArrayList<>();
        topBack.setVisibility(View.VISIBLE);
        final CrmConditionSearch conditionSearch = new CrmConditionSearch(this, enterpriseCode, appCrmSearchPartText);
        appCrmSearchPartText.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    conditionSearch.show(linearLayout1);
                } else {
                    conditionSearch.diss();
                }
            }
        });
        final CrmTimeSearch crmTimeSearch = new CrmTimeSearch(this, appCrmSearchTimeText);
        appCrmSearchTimeText.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    crmTimeSearch.show(linearLayout1);
                } else {
                    crmTimeSearch.diss();
                }
            }
        });
    }


    private void initView() {
        dialog = new ProgressDialog(this);
        dialog.setMessage("loading...");
        swipy.setOnRefreshListener(this);
        crmRecyclerView.setEmptyView(emptyview);
        crmRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        crmAdapter = new CrmAdapter(this, mDatas);
        crmRecyclerView.setAdapter(crmAdapter);
        new CrmHelper(this).initCrmInfo(enterpriseCode);//初始化搜索条件
        dialog.setMessage("loading...");
        dialog.show();
        searchCrm(khzt, khxz);
       // isAgain = true;
        //设置软键盘的搜索监听按钮
        enterpriseName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    crmAdapter.clearList();
                    //完成自己的事件
                    searchCrm(khzt, khxz);
                    KeyboardUtil.hideKeyboard(CrmActivity.this);
                    return true;
                }
                return false;
            }
        });
    }

    private void initCretaLisener() {
        CreateCrmActivity.setOnCretaCrmListener(new CreateCrmActivity.OnCretaCrmLisenter() {
            @Override
            public void onSuccess() {
                crmAdapter.clearList();
                //刷新
                searchCrm("", "");
            }

            @Override
            public void onFailed() {

            }
        });
    }

    @OnClick({R.id.topBack, R.id.calendar, R.id.add, R.id.app_crm_search_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.app_crm_search_img:
                //搜索
                crmAdapter.clearList();
                searchCrm(khzt, khxz);
                KeyboardUtil.hideKeyboard(CrmActivity.this);
                break;
            case R.id.add:
                startActivity(new Intent(this, CreateCrmActivity.class));
                break;
            case R.id.calendar:
                startActivity(new Intent(this, CrmCalendarActivity.class));
                break;
        }
    }


    //按条件搜索CRM
    public void searchCondition(List<String> list_instudry, List<String> list_state) {
        //每次搜索都设置page=1 代表初始化
        page = 1;
        khzt = list_state.toString().substring(1, list_state.toString().length() - 1).replace(" ", "");
        khxz = list_instudry.toString().substring(1, list_instudry.toString().length() - 1).replace(" ", "");
        crmAdapter.clearList();
        searchCrm(khzt, khxz);
        //是否重新设置数据
        //isAgain = true;
        //开始搜索保存搜索条件

    }


    private void searchCrm(String khzt, String khxz) {
        Log.i("test", "客户状态：" + khzt + "&&客户性质：" + khxz);
        dialog.show();
        String company = enterpriseName.getText().toString().trim();
        String encode = "";
        try {
            encode = URLEncoder.encode(company, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        CrmHttpHelper.searchCrmList(userId, page + "", "20", orderTime,
                khzt, khxz, encode, "", new CrmHttpHelper.OnCrmDetailListenter() {
                    @Override
                    public void onCrmListener(List<CrmSearchBean.ListCrm> listbean) {
                        Log.i("test", "大小：" + listbean.size());
                        mDatas.clear();
                        mDatas = listbean;
                        Log.i("test", "CRM添加:" + mDatas.size());
                        crmAdapter.addList(mDatas);
                        dialog.dismiss();
                        swipy.setRefreshing(false);
                    }

                    @Override
                    public void onEmtry() {
                        mDatas.clear();
                        crmAdapter.addList(mDatas);
                        dialog.dismiss();
                        swipy.setRefreshing(false);
                    }

                    @Override
                    public void onHintLoading() {
                        dialog.dismiss();
                        swipy.setRefreshing(false);
                    }
                });
    }

    //按时间搜索CRM  正序 false 倒序 true
    public void searchTime(boolean b) {
        if (true) {
            //倒序
            orderTime = "ldsj desc";
        } else {
            //正序
            orderTime = "ldsj  asc";
        }
        //isAgain = true;
        crmAdapter.clearList();
        searchCrm(khzt, khxz);

    }



    @Override
    public void onRefresh(SwipyRefreshLayoutDirection direction) {
        Log.i("test", "刷新");
        page = page + 1;
        searchCrm(khzt, khxz);
        //isAgain = false;

    }



}
